package es.cerosyunos.androiddevs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import android.widget.TextView;

public class CameraCaptions extends Activity{
	
	protected static final String TAG = "CAMERA=";
	public static final int MEDIA_TYPE_IMAGE = 1;
	private Camera mCamera;
	private Parameters mCamParam;
	private CameraPreview mPreview;
	private boolean mInProgress;
	private Timer timer;
	private Handler handler;
	private int mNumCaptions;
	private int mTimerBetweenCaptions;
	private int mCaptions;
	private Intent intent;
	private ArrayList<String> imagenesCapturadas;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		handler= new Handler();
		mCaptions = 0;
		setContentView(R.layout.captions);
		intent = getIntent();
		String numCaps = intent.getStringExtra(TimedCapturesActivity.EXTRA_NUM_CAPS);
		String timerCaps = intent.getStringExtra(TimedCapturesActivity.EXTRA_TIMER_CAPS);
		
        mNumCaptions = Integer.parseInt(numCaps);
        mTimerBetweenCaptions = Integer.parseInt(timerCaps);

        imagenesCapturadas = new ArrayList<String>();
		
		TextView textView = (TextView) findViewById (R.id.description);
	    textView.setTextSize(15);
	    textView.setText("Capturar " + numCaps + " imagenes con " + timerCaps + " segundos entre cada captura");
	    
	    mCamera = getCameraInstance();
	    
	    mCamParam = mCamera.getParameters();
	    
	 // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);        
        
        timeredTask();
	    
	}
	
	/** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance(){
	    Camera c = null;
	    try {
	        c = Camera.open(); // attempt to get a Camera instance
	    }
	    catch (Exception e){
	    	Log.d(TAG, "Error taking camera: " + e.getMessage());
	    }
	    return c; // returns null if camera is unavailable
	}
	
	/** A basic Camera preview class */
	public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
	    private static final String TAG = "CAMERA ";
		private SurfaceHolder mHolder;
	    private Camera mCamera;

	    public CameraPreview(Context context, Camera camera) {
	        super(context);
	        mCamera = camera;

	        // Install a SurfaceHolder.Callback so we get notified when the
	        // underlying surface is created and destroyed.
	        mHolder = getHolder();
	        mHolder.addCallback(this);
	        // deprecated setting, but required on Android versions prior to 3.0
	        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	    }

	    public void surfaceCreated(SurfaceHolder holder) {
	        // The Surface has been created, now tell the camera where to draw the preview.
	        try {
	        	holder.setKeepScreenOn(true);
	            mCamera.setPreviewDisplay(holder);
	            mCamera.startPreview();
	        } catch (IOException e) {
	            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
	        }
	    }

	    public void surfaceDestroyed(SurfaceHolder holder) {
	        // empty. Take care of releasing the Camera preview in your activity.
	    }

	    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
	        // If your preview can change or rotate, take care of those events here.
	        // Make sure to stop the preview before resizing or reformatting it.

	        if (mHolder.getSurface() == null){
	          // preview surface does not exist
	          return;
	        }

	        // stop preview before making changes
	        try {
	            mCamera.stopPreview();
	        } catch (Exception e){
	          // ignore: tried to stop a non-existent preview
	        }

	        // set preview size and make any resize, rotate or
	        // reformatting changes here

	        // start preview with new settings
	        try {
	            mCamera.setPreviewDisplay(mHolder);
	            mCamera.startPreview();

	        } catch (Exception e){
	            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
	        }
	    }
	}
	
	private PictureCallback mPicture = new PictureCallback() {

	    @Override
	    public void onPictureTaken(byte[] data, Camera camera) {

	        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
	        if (pictureFile == null){
	            Log.d(TAG, "Error creating media file, check storage permissions: ");
	            return;
	        }

	        try {
	            FileOutputStream fos = new FileOutputStream(pictureFile);
	            fos.write(data);
	            fos.close();
	        } catch (FileNotFoundException e) {
	            Log.d(TAG, "File not found: " + e.getMessage());
	        } catch (IOException e) {
	            Log.d(TAG, "Error accessing file: " + e.getMessage());
	        }
	    }
	};
	
	@Override
    protected void onPause() {
        super.onPause();
        releaseCamera();              // release the camera immediately on pause event
        timer.cancel();//esto finaliza el hilo
    }


    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
    
    /** Create a File for saving an image or video */
    private File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),"TimedCaptions");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
            imagenesCapturadas.add(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
        } else {
            return null;
        }
        
        mCaptions++;
        mCamera.startPreview();
        
    	if (mNumCaptions <= mCaptions){
    		mInProgress = false;    		
    		Bundle bundle = new Bundle();
    		bundle.putStringArrayList("IMGCAP", imagenesCapturadas);
    		Intent mIntent = new Intent();
	    	mIntent.putExtras(bundle);
	    	setResult(Activity.RESULT_OK, mIntent);
	    	finish();
        }
        
        
        return mediaFile;
    }
    
    public void timeredTask(){
        mInProgress = true;
 
        TimerTask captionTask = new TimerTask(){
            @Override
            public void run() {
 
                handler.post(new Runnable(){
                    public void run() {
                    	/*Action to execute*/
                    	mCamera.takePicture(null, null, mPicture);                    	
                    };
                });
 
                if(!mInProgress){
                    timer.cancel();//esto finaliza el hilo                    
                }
            }
        };
 
        timer = new Timer();
        timer.schedule(captionTask, mTimerBetweenCaptions*1000,mTimerBetweenCaptions*1000);//se crea un hilo
 
    }
}


